package com.tan.controller;

import com.tan.mapper.util.PageUtil;
import com.tan.model.AirQualityIndex;
import com.tan.model.District;
import com.tan.service.AirQualityIndexService;
import com.tan.service.DistrictService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class AllController {

    @Resource
    AirQualityIndexService aqis;

    @Resource
    DistrictService ds;

    @RequestMapping("/toShow")
    public ModelAndView toShow(ModelAndView mav, @RequestParam(value = "page",required = false)String page){
        mav.setViewName("/show");

        //i 为页数  接收页数:
        int i = 0;
        //判断页数是否为空
        if (page!=null) {
            //不为空转换类型赋值给 i
             i=Integer.parseInt(page);
        }
        //创建分页类
        PageUtil pageUtil = new PageUtil();
        //给类赋值
        pageUtil.setSum(aqis.getCount());
        pageUtil.setPage(i);

        //每页的第一条数据的序号
        pageUtil.setFirstPage(i*pageUtil.getPageNum());
        //每页的最后一条数据的序号
        pageUtil.setLastPage((i+1)*pageUtil.getPageNum());
        //赋值总页数
        pageUtil.setPageSum(pageUtil.getSum()%pageUtil.getPageNum()==0?pageUtil.getSum()/pageUtil.getPageNum():pageUtil.getSum()/pageUtil.getPageNum()+1);
        //获取当前页的数据并赋值给分页类
        List<AirQualityIndex> allAirQuality = aqis.getAllAirQuality(pageUtil);
        pageUtil.setAllAirQuality(allAirQuality);
        //添加数据到视图
        mav.addObject("pageUtil",pageUtil);
        return mav;
    }

    @RequestMapping("/del")
    public String del(@RequestParam(value = "id",required = false) int id){
        //根据删除
        aqis.delById(id);
        //重定向回主页面
        return "redirect:/toShow";
    }

    @RequestMapping("/add")
    public ModelAndView toAdd(ModelAndView mav){
        mav.setViewName("/add");
        List<District> allDistrict = ds.getAllDistrict();
        mav.addObject("districtList",allDistrict);
        return mav;
    }

    @PostMapping("/addQualityIndex")
    public String Add(AirQualityIndex qualityIndex){
        aqis.addAirQuality(qualityIndex);
        return "redirect:/toShow";
    }

}
